<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasDateTimeFormatter, HasApiTokens, Notifiable;

    protected $fillable = [
        'account',
        'phone',
        'mail',
        'openid',
        'unionid',
        'password',
        'nickname',
        'avatarurl',
        'gender',
        'identity',
        'status',
        'session_key',
        'keyword',
        'last_login_time',
    ];

    public static $EnumStatus = [0 => '正常', 1 => '禁止登录', 2 => '待审核'];
    public static $EnumGender = [0 => '女', 1 => '男', 2 => '未知'];
    public static $EnumIdentity = [0 => '用户', 1 => '货代'];

    public function forwarder()
    {
        return $this->hasOne('App\Models\Forwarder', 'user_id', 'id');
    }

    public function account()
    {
        return $this->hasOne('App\Models\Account', 'user_id', 'id');
    }

    protected static function booted()
    {
        static::created(function ($user) {
            $account = new Account();
            $user->account()->save($account);

            $room = new ChatRoom();
            $room->save();
            ChatRoomUser::insert([['user_id' => 11, 'room_id' => $room->id], ['user_id' => $user->id, 'room_id' => $room->id]]);
            ChatMessage::insert(['user_id' => 11, 'room_id' => $room->id, 'content' => "欢迎使用慧连易运！！", 'type' => 0]);

        });
    }

    public static function getCacheUser($id)
    {
        return Cache::rememberForever('user-' . $id, function () use ($id) {
            return User::find($id);
        });
    }
}
